package com.miplus.ccrm.admin.controller;

import com.miplus.ccrm.admin.controller.vo.*;
import com.miplus.ccrm.admin.service.SysUserService;
import com.miplus.ccrm.admin.utils.SpringContextUtil;
import com.miplus.ccrm.common.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
* 1-1.签入签出及权限管理
 */
@Slf4j
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Resource
    private SysUserService sysUserService;

    @Resource
    private JDataService dataService;

    private HttpServletRequest getHttpRequest()
    {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 用户账号签入
     */
    @PostMapping("/signin")
    public R<UserSignInResVo> signinUser(@RequestBody @Validated UserSignInReqVo signInReqVo) {
        return R.Success(sysUserService.doSignIn(signInReqVo,
                JPubUtils.getReqIpAddr(getHttpRequest())
        ));
    }

    /**
    * 用户账号签出
     */
    @PostMapping("/signdown")
    public R<Object> signDownUser() {
        EnumRCode rCode=sysUserService.doSignDown(JPubUtils.getToken(getHttpRequest()));
        if(rCode!=EnumRCode.Success){
            return R.Error(rCode);
        }
        return R.Success();
    }

    /**
     * Token验证
     */
    @PostMapping("/verify")
    public R<Object> tokenVerify() {
        return R.Success();
    }

    /**
     * 取用户信息及管理组
     */
    @GetMapping("/getusrinfo")
    public R<UserInfoResVo> getUsrInfo() {

        HttpServletRequest h=((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token= JPubUtils.getToken(h);
        String key = JPubUtils.getTokenKey(token);
        JSysUser user=(JSysUser) dataService.get(key);

        String usrid=user.getUsrid();
        UserInfoResVo resVo=sysUserService.quyUserInfo(usrid,false);
        resVo.setIsdefaultpwd(user.getIsdefaultpwd());
        if(resVo==null){
            return R.Error(EnumRCode.NoFindUsr);
        }
        return R.Success(resVo);
    }
}
